package com.bw.ann;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.bw.domain.TLog;
import com.bw.mapper.TLogMapper;
import com.bw.service.TLogService;
import com.bw.utils.common.JWTUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * @author bobo棒
 * @date 2023年10月30日 16:30
 */

@Aspect //标记该类为切面类
@Component
public class MyAop {
    @Autowired
    HttpServletRequest request;
    @Autowired
    TLogMapper tLogMapper;
//6.拦截内容包含:访问用户,ip,url,请求参数,访问时间（10分）
    // @Around 环绕通知. 拦截  方法上标记MyAnn 的注解
    @Around("@annotation(MyAnn)")
    public Object  log(ProceedingJoinPoint pjp) throws Throwable {
        //1.访问用户
        String username = JWTUtils.getUsername();
       if(ObjectUtils.isEmpty(username)){
           System.out.println("访问用户:用户正在登录");
       }else{
           System.out.println("访问用户:"+username);
       }
       //2 ip
        String ip = request.getRemoteAddr();
        System.out.println("ip:"+ip);
       //3url
        String url = request.getRequestURL().toString();
        System.out.println("url:"+url);
       //4 请求参数
        Object[] args = pjp.getArgs();
        System.out.println("args:"+JSONUtil.toJsonStr(args));
     //5.访问时间
        System.out.println("访问时间:"+new Date());
        TLog tLog = new TLog();
        tLog.setArgs(JSONUtil.toJsonStr(args));
        tLog.setIp(ip);
        tLog.setUrl(url);
        tLog.setCratedTime(new Date());
        tLogMapper.insert(tLog);
        Object proceed = pjp.proceed();
        return proceed;
    }
}
